package com.ptszyxx.popose.module.main.mine;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.lifecycle.ViewModelProviders;
import com.alipay.sdk.app.PayTask;
import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.databinding.FragmentMineVipBinding;
import com.ptszyxx.popose.module.main.mine.adapter.MineVipAdapter;
import com.ptszyxx.popose.module.main.mine.vm.MineVipVM;
import com.ysg.base.BaseActivity;
import com.ysg.enums.PayEnum;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.mine.VipEntity;
import com.ysg.http.data.entity.mine.VipUserEntity;
import com.ysg.utils.YConfigUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YImageUtil;
import com.ysg.utils.YRecyclerViewUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.dialog.PayDialog;
import java.util.List;
import java.util.Map;

/**
 * Vip充值
 */
public class MineVipFragment extends BaseActivity<FragmentMineVipBinding, MineVipVM> {
    private MineVipAdapter adapter;

    public static MineVipFragment getInstance() {
        return new MineVipFragment();
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.fragment_mine_vip;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MineVipVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MineVipVM.class);
    }

    @Override
    public void onResume() {
        super.onResume();
        viewModel.requestVip();
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        adapter = new MineVipAdapter(viewModel);
        YRecyclerViewUtil.initGrid(MineVipFragment.this, binding.recyclerView, adapter, 3);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, o -> setAdapterData((List<VipEntity>)o));
        viewModel.uc.onRefreshItemEvent.observe(this, o -> setBtnUI());
        viewModel.uc.onOtherEvent.observe(this, o -> seOtherUI());
        viewModel.uc.onPayDialogEvent.observe(this, o -> showDialogPay());
        viewModel.uc.onVipPrivilegeDialogEvent.observe(this, o -> showDialogVipPrivilege((String)o));
        viewModel.uc.onAlipayEvent.observe(this, o -> startAlipay());
    }

    private void setAdapterData(List<VipEntity> list) {
        adapter.setList(list);
    }

    private void setBtnUI() {
        adapter.setPosition(viewModel.currentPosition);

        if (viewModel.vipResult == null){
            return;
        }
        if (YStringUtil.eq(1, viewModel.vipResult.getUser().getIsVip())) {
            binding.tvOpen.setText(getResources().getString(R.string.currency) + viewModel.currentEntity.getPrice() + getResources().getString(R.string.mine_vip_btn_renew));
        } else {
            binding.tvOpen.setText(getResources().getString(R.string.currency) + viewModel.currentEntity.getPrice() + getResources().getString(R.string.mine_vip_btn_open));
        }
    }

    private void seOtherUI() {
        if (viewModel.vipResult.getUser() == null){
            return;
        }
        VipUserEntity user = viewModel.vipResult.getUser();
        YImageUtil.show(binding.ivHead, user.getPic());
        if (YStringUtil.eq(1, user.getIsVip())) {
            String format = String.format(getResources().getString(R.string.mine_vip_status_open), user.getVipEndDate());
            binding.tvVipStatus.setText(format);
        } else {
            binding.tvVipStatus.setText(getResources().getString(R.string.mine_vip_status_unopen));
        }
    }

    private void showDialogPay() {
        if (!viewModel.privacyChecked.get()){
            YToastUtil.showShort(R.string.recharge_agreement_check_tip);
            return;
        }

        VipEntity currentEntity = viewModel.currentEntity;
        if (currentEntity == null){
            return;
        }
        YDialogUtil.getInstance().showPay(MineVipFragment.this, currentEntity.getPrice()+"")
                .setOnPayListener(new PayDialog.OnPayListener() {

                    @Override
                    public void onPay(PayEnum payEnum) {
                        if (PayEnum.wechat == payEnum){
                            viewModel.requestPay("2", currentEntity.getId());
                        }else{
                            if (YConfigUtil.getPayApp()){
                                viewModel.requestPayApp("1", currentEntity.getId());
                            }else{
                                viewModel.requestPay("1", currentEntity.getId());
                            }
                        }
                    }
                });
    }

    private void showDialogVipPrivilege(String type) {
        YDialogUtil.getInstance().showVipPrivilege(MineVipFragment.this, type);
    }

    private Runnable payRunnable = new Runnable() {
        @Override
        public void run() {
            PayTask alipay = new PayTask(MineVipFragment.this);
            Map<String,String> result = alipay.payV2(viewModel.orderInfo,true);
            Message msg = new Message();
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    // 必须异步调用
    private void startAlipay(){
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            String resultStatus = payResult.getResultStatus();
            if (TextUtils.equals(resultStatus, "9000")) {
                YToastUtil.showShort("支付成功");
            } else {
                YToastUtil.showShort("支付失败");
            }
        }
    };

}
